
package com.lsq.wuyuge.common.exception;

import com.lsq.wuyuge.common.result.Result;
import com.lsq.wuyuge.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalException {
    /**
     * 数据库异常
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResponseEntity<Result<?>> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String name = split[2];
            String msg = name + " " + ResultCode.UNAUTHORIZED;
            return new ResponseEntity<>(Result.failed(401, msg), HttpStatus.OK); // 返回自定义的Result对象，状态码为200
        } else {
            return new ResponseEntity<>(Result.failed(ResultCode.SYSTEM_ERROR.getCode(), ResultCode.SYSTEM_ERROR.getMessage()), HttpStatus.OK); // 返回自定义的Result对象，状态码为200
        }
    }

    /**
     * 所有异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result<?>> handleException(Exception e) {
        log.error("异常信息：{}", e.getMessage());
        return new ResponseEntity<>(Result.failed(ResultCode.SYSTEM_ERROR.getCode(), e.getMessage()), HttpStatus.OK); // 返回自定义的Result对象，状态码为200
    }

    /**
     * 处理用户名或密码错误的异常
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Result<?>> handleRuntimeException(RuntimeException e) {
        log.error("异常信息：{}", e.getMessage());
        if ("用户名或密码错误！".equals(e.getMessage())) {
            return new ResponseEntity<>(Result.failed(401, "用户名或密码错误！"), HttpStatus.OK); // 返回自定义的Result对象，状态码为200
        }
        return new ResponseEntity<>(Result.failed(ResultCode.SYSTEM_ERROR.getCode(), e.getMessage()), HttpStatus.OK); // 返回自定义的Result对象，状态码为200
    }
}
